﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace YouxinHelper.Helper.Currency
{
    class RequestPage
    {
        private static CookieContainer m_Cookie = new CookieContainer();
       

        /// <summary>  
        /// 获取页面内容，保存CookieHeader  
        /// </summary>  
        /// <returns></returns>  
        public static string InitGetPageContent(String Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.UserAgent = StaticValue.UserAgent;
            request.CookieContainer = m_Cookie;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            
            string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(Url));
            m_Cookie.SetCookies(new Uri(Url), cookieheader);

            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string result = reader.ReadToEnd();

            stream.Close();
            reader.Close();
            response.Close();

            return result;
        }

        /// <summary>  
        /// 获取页面内容，存储CookieContainer  
        /// </summary>  
        /// <param name="url">被请求页面的url</param>  
        /// <returns>返回页面内容</returns>  
        public static string GetPageContent(string url)
        {
            StringBuilder result = new StringBuilder("");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = StaticValue.UserAgent;
            HttpWebResponse reponse = null;
            try
            {
                request.CookieContainer = m_Cookie;
                reponse = (HttpWebResponse)request.GetResponse();
                m_Cookie = request.CookieContainer;
                Stream rspStream = reponse.GetResponseStream();
                StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.Default);

                //获取数据  
                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    result.Append(read, 0, count);
                    count = sr.Read(read, 0, 256);
                }
            }
            catch (Exception e)
            {
                result.Append(e.Message);
            }
            finally
            {
                if (reponse != null)
                {
                    reponse.Close();
                }
            }
            return result.ToString();
        }
    }
}
